package com.tanhua.dubbo.server.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.pojo.SoundTime;
import com.tanhua.dubbo.server.service.IdService;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class SoundApiImpl implements SoundApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 保存语音
     *
     * @param sound
     * @return
     */
    @Override
    public String saveSound(Sound sound) {
        try {
            // 校验 如果查询数据为空, 则直接返回null
            if (!ObjectUtil.isAllNotEmpty(sound.getUserId(), sound.getSoundUrl())) {
                return null;
            }

            // 设置id
            sound.setId(ObjectId.get());
            sound.setVid(idService.createId(IdType.SOUND));
            // 发布时间
            sound.setCreated(System.currentTimeMillis());
            // 保存到MongoDB中
            mongoTemplate.save(sound);
            return sound.getId().toHexString();
        } catch (Exception e) {
            log.error("语音发布失败~ video = " + sound, e);
        }
        return null;
    }

    /**
     * 接收语音
     *
     * @param userId
     * @return
     */
    @Override
    public SoundTime querySoundByUserId(Long userId) {
        // 查询用户今天是否已经接收语音, 如果已经接收则不记录
        SoundTime soundTime = new SoundTime();
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();

        Query query = Query.query(Criteria.where("userId").is(userId)
                // 时间大于等于最小时间, 小于等于最大时间
                .andOperator(Criteria.where("created").gte(minDate), Criteria.where("created").lte(maxDate)));
        long count = mongoTemplate.count(query, SoundTime.class);

        if (count > 0) {
            Update update = new Update();
            update.inc("number", -1);
            Query queryNumber = Query.query(Criteria.where("userId").is(userId)
                    .andOperator(Criteria.where("created").gte(minDate), Criteria.where("created").lte(maxDate)));
            mongoTemplate.updateFirst(queryNumber, update, SoundTime.class);
            Query queryUserId = Query.query(Criteria.where("userId").is(userId)
                    .andOperator(Criteria.where("created").gte(minDate), Criteria.where("created").lte(maxDate)));
            return mongoTemplate.findOne(queryUserId, SoundTime.class);
        }

        soundTime.setId(ObjectId.get());
        soundTime.setUserId(userId);
        soundTime.setCreated(System.currentTimeMillis());
        soundTime.setNumber(8);
        mongoTemplate.save(soundTime);
        return soundTime;
    }

    /**
     * 从语音库接收语音
     *
     * @return
     */
    @Override
    public List<Sound> querySounds() {
        return mongoTemplate.findAll(Sound.class);
    }

    /**
     * 加为好友后删除语音库中两个人的语音
     *
     * @param userId  登录用户id
     * @param likeUserId  好友id
     */
    @Override
    public void deleteSound(Long userId, Long likeUserId) {
        Query query1 = Query.query(Criteria.where("userId").is(userId));
        mongoTemplate.remove(query1, Sound.class);
        Query query2 = Query.query(Criteria.where("userId").is(likeUserId));
        mongoTemplate.remove(query2, Sound.class);
    }
}
